<?php


namespace app\auth\service;


use app\common\models\AdminGroupModel;
use app\common\models\AdminModel;
use think\facade\Db;

class AdminUserService extends BaseService
{
    protected $model;
    public function __construct()
    {
        $this->model = new AdminModel();
        parent::__construct();
    }

    public function getData($params,$page,$pageSize) {
        $condition = $this->getCondition($params);
        $count = $this->model->where($condition)-> count();
        $data = $this->model->where($condition)->order('id desc')->page($page,$this->pageSize)->select();
        $userIdList = [];
        foreach ($data as $val) {
            $userIdList[] = $val['id'];
        }
        // 根据用户ID获取用户的角色
        $groupService = new GroupService();
        $userGroup = $groupService->getGroupNameByList($userIdList);
        foreach ($data as &$val) {
            $val['group'] = '';
            if(isset($userGroup[$val['id']])) {
                $val['group'] = $userGroup[$val['id']];
            }
//            $val['group'] = $userGroup[$val['id']];
        }
        return ['count' => $count,'data' => $data];
    }

    /**
     * 获得Condition
     * @param $params
     */
    public function getCondition($params)
    {
        $condition = [
            'del_flag' => 0
        ];

        return $condition;
    }

    /**
     * 添加用户
     */
    public function addUser($params) {
        $adminGroupModel = new AdminGroupModel();
        // 判断用户名是否重复
        $condition = [
            'del_flag' => 0,
            'user_name' => $params['userName']
        ];
        $count = $this->model->where($condition)->count();
        if($count > 0) {
            return ['code' => 2,'msg' => '用户名重复!'];
        }
        Db::startTrans();
        $data = [
            'user_name' => $params['userName'],
            'password' => password_hash($params['password'],PASSWORD_DEFAULT),
            'name' => $params['name'],
            'status' => 1,
            'head_url' => $params['head_url']
        ];
        try {
            $userId = $this->model->insertGetId($data);
        }catch (\Exception $e) {
            Db::rollback();
            return ['code' => 1,'msg' => '添加用户失败'];
        }
        // 添加用户的角色，一个用户可以有多个角色
        try {
            $userGroupData = [
                'user_id' => $userId,
                'group_id' => $params['group']
            ];
            $adminGroupModel->insert($userGroupData);
        }catch (\Exception $e) {
            Db::rollback();
            return ['code' => 1,'msg' => '添加用户角色失败'];
        }

        Db::commit();
        if($userId > 0) {
            return ['code' => 0,'msg' => '操作成功','data' => $userId];
        }else {
            return ['code' => 1,'msg' => '操作失败'];
        }
    }

    /**
     * 编辑用户
     * @param $params
     */
    public function editUser($params) {
        $adminGroupModel = new AdminGroupModel();
        // 判断用户名是否重复
        $condition = [
            ['del_flag','=',0],
            ['user_name','=',$params['userName']],
            ['id','<>',$params['id']]
        ];
        $count = $this->model->where($condition)->count();
        if($count > 0) {
            return ['code' => 2,'msg' => '用户名重复!'];
        }

        Db::startTrans();
        $data = [
            'user_name' => $params['userName'],
            'name' => $params['name'],
            'status' => 1,
            'head_url' => $params['head_url']
        ];
        if(!empty($params['password'])) {
            $data['password'] = password_hash($params['password'],PASSWORD_DEFAULT);
        }
        try {
            $userId = $this->model->where(['id' => $params['id']])->save($data);
        }catch (\Exception $e) {
            Db::rollback();
            return ['code' => 1,'msg' => '添加用户失败'];
        }
        try {
            // 添加用户的角色，一个用户可以有多个角色
            $condition = [
                'user_id' => $params['id']
            ];
            $adminGroupModel->where($condition)->save(['del_flag' => 1]);
            $userGroupData = [
                'user_id' => $params['id'],
                'group_id' => $params['group']
            ];
            $adminGroupModel->insert($userGroupData);
        }catch (\Exception $e) {
            Db::rollback();
            return ['code' => 1,'msg' => '添加用户角色失败'];
        }
        Db::commit();
        if($userId !== false) {
            return ['code' => 0,'msg' => '操作成功','data' => $userId];
        }else {
            return ['code' => 1,'msg' => '操作失败'];
        }
    }

    /**
     * 删除用户
     */
    public function delUser($id) {
        $where = [
            'id' => $id
        ];
        $updateData = [
            'del_flag' => 1
        ];
        $res = $this->modify($where,$updateData);
        return $res;
    }

    /**
     * 获取用户的角色
     */
    public function getUserGroup($userId) {
        $condition = [
            'user_id' => $userId
        ];
        $model = new AdminGroupModel();
        $data = $model->where($condition)->field('group_id')->find();
        if($userId > 1) {
            return $data['group_id'];
        }
        return 0;
    }

    /**
     * 获取用户的详细信息
     * @param $userId
     * @return array|void
     */
    public function detail($userId) {
        $data = $this->model->where(['id' => $userId])->find();
        $group = self::getUserGroup($userId);
        $data['group'] = $group;
        return $data;
    }

    /**
     * 修改个人信息
     * @param $params
     */
    public function persional($params) {
        $data = [
            'user_name' => $params['userName'],
            'name' => $params['name'],
        ];

        if(!empty($params['password'])) {
            $data['password'] = password_hash($params['password'],PASSWORD_DEFAULT);
        }

        $res = $this->model->where(['id' => $params['id']])->save($data);
        if($res !== false) {
            $admin = $this->model->where(['id' => $params['id']])->find();
            $adminUserService = new AdminUserService();
            $group = $adminUserService->getUserGroup($admin['id']);
            $admin['group'] = $group;
            session('admin',$admin);
            return ['code' => 0,'msg' => '操作成功'];
        }else {
            return ['code' => 1,'msg' => '操作失败'];
        }
    }

	/**
	 * 获取用户
	 * @return \think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
    public function getUser() {
    	$condition = $this->initCondition();
    	$condition[] = ['status','=', 1];
		return $this->model->where($condition)->field('id,name,user_name')->select();
	}

	/**
	 * 根据后台用户ID，获取后台用户信息
	 * @param $list
	 */
	public function getAdminUserByList($list) {
		if(count($list) == 0) return [];
		$condition = $this->initCondition();
		$condition[] = ['status','=', 1];
		$condition[] = ['id','IN', $list];
		return $this->model->where($condition)->column('id,name,user_name','id');
	}

}